<template>
  <div class="user-center">
    <h2 style="text-align: center">个人资料</h2>
    <!-- 头像展示 -->
    <div class="avatar-section">
      <img :src="user.imageUrl" alt="用户头像" class="avatar">
      <el-upload
          class="avatar-upload"
          :action="uploadTarget + '/common/files/upload'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess">
        <el-button size="small">更换头像</el-button>
      </el-upload>
    </div>

    <!-- 个人信息表单 -->
    <el-form ref="form" :model="user" :rules="rules" label-width="100px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="user.username" :disabled="!isEditing"></el-input>
      </el-form-item>

      <el-form-item label="真实姓名" prop="name">
        <el-input v-model="user.name" :disabled="!isEditing"></el-input>
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="user.email" :disabled="!isEditing"></el-input>
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input v-model="user.phone" :disabled="!isEditing"></el-input>
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-select v-model="user.gender" :disabled="!isEditing">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="积分">
        <el-input v-model="user.points" disabled></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleEdit" v-if="!isEditing">编辑信息</el-button>
        <el-button type="success" @click="handleSave" v-else>保存修改</el-button>
        <el-button @click="cancelEdit" v-if="isEditing">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {getPersonInfo, updatePersonInfo,} from "@/api/request/WebRequest";

export default {
  name: "CenterView",
  data() {
    return {
      isEditing: false,
      uploadTarget: process.env.VUE_APP_BASEURL,
      userInfo: {},
      user: {
        id: null,
        username: null,
        name: null,
        email: null,
        imageUrl: null,
        phone: null,
        gender: null,
      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ],
        gender: [
          {required: true, message: "请选择性别", trigger: "blur"}
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {pattern: /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/, message: '请输入正确的邮箱格式', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur'}
        ]
      },

    };
  },
  methods: {
    handleEdit() {
      this.isEditing = true;
    },
    handleSave() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          updatePersonInfo({
            id: this.user.id,
            username: this.user.username,
            name: this.user.name,
            email: this.user.email,
            imageUrl: this.user.imageUrl,
            phone: this.user.phone,
            gender: this.user.gender
          }).then(res => {
            if (res.code !== 200) {
              this.$message.error(res.msg);
              return;
            }

            this.$message.success('修改成功');

            localStorage.setItem('xm-user', JSON.stringify({...res.data, token: this.userInfo.token}))
            setTimeout(() => {
              window.location.reload(true);
            }, 500)
          }).catch(error => {
            console.log(error)
          });
        }
      })
    },
    cancelEdit() {
      this.isEditing = false;
    },
    handleAvatarSuccess(res) {
      this.user.imageUrl = res.data;
      console.log(this.user)
      updatePersonInfo({id: this.userInfo.id, imageUrl: res.data}).catch(error => {
        console.log(error)
      });
    },
    getUserInfo() {
      getPersonInfo(this.userInfo.id).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.msg);
          return;
        }

        this.user = res.data
      }).catch(error => {
        console.log(error)
      });
    }
  },
  mounted() {
    this.userInfo = JSON.parse(localStorage.getItem('xm-user'))
    this.getUserInfo()
  }
};
</script>

<style scoped lang="scss">
.user-center {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  background: #fff;
  border-radius: 8px;

  .avatar-section {
    text-align: center;
    margin-bottom: 30px;

    .avatar {
      width: 120px;
      height: 120px;
      border-radius: 50%;
      margin-bottom: 10px;
    }
  }

  ::v-deep .el-form-item__label {
    font-weight: bold;
  }
}
</style>
